/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 */

import React, {useEffect, useState, memo} from 'react';
import {
  SafeAreaView,
  StatusBar,
  StyleSheet,
  Switch,
  useColorScheme,
} from 'react-native';

import {Colors} from 'react-native/Libraries/NewAppScreen';
import HttpClient from './src/network/httpClient';
import {
  ErrBoundary,
  LineChart,
  BasePage,
  TableView,
} from './src/components/index';
import {PositionType, useLocation} from './src/hooks/home';
import {combineArray} from './src/utils/common';
const httpClient = new HttpClient();

function App(): React.JSX.Element {
  const isDarkMode = useColorScheme() === 'dark';
  const [isLoading, setLoading] = useState<boolean>(true);
  const [isError, setError] = useState<boolean>(false);
  const [isChart, setIsChart] = useState(false);

  const [x, setX] = useState<string[]>([]);
  const [y, setY] = useState<number[]>([]);
  const {position, error} = useLocation();

  useEffect(() => {
    error && setError(error);
    !error && position && requestTemperatur(position);

    return () => {
      // 在组件卸载时取消请求
      cancelRequest();
    };
  }, [position]);

  // 取消请求
  const cancelRequest = () => {
    httpClient.cancelRequest();
  };

  // 请求气温数据
  const requestTemperatur = (position: PositionType) => {
    const url = `https://api.open-meteo.com/v1/forecast?latitude=${position.latitude}&longitude=${position.longitude}&hourly=temperature_2m`;
    // 示例：发送 GET 请求
    httpClient
      .get<{id: number; title: string}[]>(url)
      .then((data: any) => {
        setLoading(false);
        let {temperature_2m = [], time = []} = data?.hourly;
        setX(time);
        setY(temperature_2m);
      })
      .catch(() => setError(true));
  };

  const backgroundStyle = {
    backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
  };

  const reload = () => {
    setLoading(true);
    requestTemperatur(position);
  };

  const toggleSwitch = () => {
    setIsChart(previousState => !previousState);
  };

  return (
    <SafeAreaView style={[backgroundStyle, styles.container]}>
      <StatusBar
        barStyle={isDarkMode ? 'light-content' : 'dark-content'}
        backgroundColor={backgroundStyle.backgroundColor}
      />
      <ErrBoundary>
        <BasePage isError={isError} isLoading={isLoading} reload={reload}>
          <Switch
            style={styles.switchBtn}
            trackColor={{false: '#767577', true: '#81b0ff'}}
            thumbColor={'#f4f3f4'}
            ios_backgroundColor="#3e3e3e"
            onValueChange={toggleSwitch}
            value={isChart}
          />
          {isChart && <LineChart x={x} y={y} />}
          {!isChart && <TableView data={combineArray(x, y)} />}
        </BasePage>
      </ErrBoundary>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#fff',
  },
  switchBtn: {
    position: 'absolute',
    bottom: 0,
    right: 20,
    zIndex: 1,
  },
});

export default memo(App);
